package com.lu.task.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lu.common.config.Constant;
import com.lu.common.quartz.utils.QuartzManager;
import com.lu.common.utils.PageUtils;
import com.lu.common.utils.ScheduleJobUtils;
import com.lu.system.management.dao.UserDao;
import com.lu.system.management.domain.UserDO;
import com.lu.task.domain.ScheduleJob;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lu.task.dao.TaskDao;
import com.lu.task.domain.TaskDO;
import com.lu.task.service.TaskService;

@Service
public class TaskServiceImpl implements TaskService {

	private static String preBeanClass = "com.lu.task.instance.";

	@Autowired
	private TaskDao taskDao;
	@Autowired
	private QuartzManager quartzManager;
	@Autowired
	private UserDao userDao;
	
	@Override
	public TaskDO get(Long id){
		return taskDao.get(id);
	}
	
	@Override
	public List<TaskDO> list(Map<String, Object> map){
		return taskDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return taskDao.count(map);
	}
	
	@Override
	public int save(TaskDO task){
		return taskDao.save(task);
	}

    @Override
    public void saveBatch(List<TaskDO> task) throws Exception {
		taskDao.saveBatch(task);
    }
	
	@Override
	public int update(TaskDO task){
		task.setBeanClass(preBeanClass+task.getMethodName());
		return taskDao.update(task);
	}

    @Override
    public void updateBatch(List<TaskDO> task) throws Exception {
		taskDao.updateBatch(task);
    }
	
	@Override
	public int remove(Long id){
		return taskDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return taskDao.batchRemove(ids);
	}

	@Override
	public void initSchedule() throws SchedulerException {
		// 这里获取任务信息数据
		List<TaskDO> jobList = taskDao.list(new HashMap<String, Object>(16));
		for (TaskDO scheduleJob : jobList) {
			if ("1".equals(scheduleJob.getJobStatus())) {
				ScheduleJob job = ScheduleJobUtils.entityToData(scheduleJob);
				quartzManager.addJob(job);
			}

		}
	}

	@Override
	public void changeStatus(Long jobId, String cmd) throws SchedulerException {
		TaskDO scheduleJob = get(jobId);
		if (scheduleJob == null) {
			return;
		}
		if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
			quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
			scheduleJob.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
		} else {
			if (!Constant.STATUS_RUNNING_START.equals(cmd)) {
			} else {
				scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
				quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
				quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob));
			}
		}
		update(scheduleJob);
	}

	@Override
	public void updateCron(Long jobId) throws SchedulerException {
		TaskDO scheduleJob = get(jobId);
		if (scheduleJob == null) {
			return;
		}
		if (ScheduleJob.STATUS_RUNNING.equals(scheduleJob.getJobStatus())) {
			quartzManager.updateJobCron(ScheduleJobUtils.entityToData(scheduleJob));
		}
		update(scheduleJob);
	}

	@Override
	public PageUtils getTaskList(Map<String, Object> map, Integer page, Integer limit) throws Exception{
		PageHelper.startPage(page, limit);
		List<TaskDO> lists=taskDao.list(map);
		//!=null是系统管理员的查看
		Long userId = (Long) map.get("userId");
		if(userId==null){
			for(TaskDO list : lists){
				list.setUserDO(userDao.get(list.getUserId()));
			}
		}
		//获取所有计划中的任务列表
		List<ScheduleJob> getRunningJobList = null;
		try {
			getRunningJobList = quartzManager.getRunningJob();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		for(TaskDO list : lists){
//			String nextTaskTime = getNextTaskTime(list.getCronExpression());
			for(ScheduleJob getRunningJob : getRunningJobList){
				if(list.getJobName().equals(getRunningJob.getJobName())&&list.getJobGroup().equals(getRunningJob.getJobGroup())){
					list.setJobStatus("执行任务中");
					continue;
				}
			}
		}
		PageInfo<List<TaskDO>> pageInfos = new PageInfo(lists);
		PageUtils pageUtil = new PageUtils(lists, new Long(pageInfos.getTotal()).intValue());
		return pageUtil;
	}

	@Override
	public Integer saveJob(TaskDO taskDO,UserDO userDO) throws Exception{
		taskDO.setBeanClass(preBeanClass+taskDO.getMethodName());
		taskDO.setJobStatus("1");
		taskDO.setUserId(userDO.getUserId());
		taskDO.setCreateBy(userDO.getUsername());
		if(taskDO.getSrcEmailPassword().equals("******")){
			taskDO.setSrcEmailPassword("******");
		}else{
			taskDO.setSrcEmailPassword(taskDO.getSrcEmailPassword());
		}
//		taskDO.setTargetTime();
//		taskDO.setTargetTimeFrame(0);
//		taskDO.setTargetTimeFrameUnit("天");
		int res = this.save(taskDO);
		if(res==1){
			if (ScheduleJob.STATUS_RUNNING.equals(taskDO.getJobStatus())) {
				ScheduleJob job = ScheduleJobUtils.entityToData(taskDO);
				quartzManager.addJob(job);
			}
			return res;
		}
		return null;
	}

	@Override
	public Integer updateJob(TaskDO taskDO) throws Exception{
		TaskDO scheduleJob = get(taskDO.getId());
		if (scheduleJob == null) {
			return null;
		}
		taskDO.setUpdateDate(new Date());
		int res = update(taskDO);
		if(res==0){
			return null;
		}
		TaskDO scheduleJob2 = get(taskDO.getId());
		//获取所有计划中的任务列表
		List<ScheduleJob> getRunningJobList = null;
		try {
			getRunningJobList = quartzManager.getRunningJob();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob2));
		quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob2));
//		for(ScheduleJob getRunningJob : getRunningJobList){
//			if(getRunningJob.getJobGroup().equals(scheduleJob2.getJobGroup())&&getRunningJob.getJobName().equals(scheduleJob2.getJobName())){
//				quartzManager.updateJobCron(ScheduleJobUtils.entityToData(scheduleJob2));
//				break;
//			}else{
//				quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob2));
//				break;
//			}
//		}
		return res;
	}

	@Override
	public Integer removeJob(Long id) throws Exception{
		TaskDO scheduleJob = get(id);
		//删除空的也不会保存
		quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
		int res = this.remove(id);
		if(res==0){
			return null;
		}
		return res;
	}


}
